<template>
  <el-form class="login-form"
           status-icon
           :rules="registerRules"
           ref="loginForm"
           :model="loginForm"
           label-width="0">
    <!--    <el-form-item v-if="tenantMode" prop="tenantId">
          <el-input size="small"
                    @keyup.enter.native="handleLogin"
                    v-model="loginForm.tenantId"
                    auto-complete="off"
                    :placeholder="$t('login.tenantId')">
            <i slot="prefix" class="icon-quanxian"/>
          </el-input>
        </el-form-item>-->
    <el-form-item prop="roleId">
      <!--      <el-select v-model="loginForm.roleId" placeholder="请选择注册类型" style="width: 100%">
              <el-option label="医疗机构/药店" value="1682730217149665281"></el-option>
              <el-option label="企业" value="1682730323424940034"></el-option>
            </el-select>-->
      <div style="color: black">您将注册为：</div>
      <el-radio-group v-model="loginForm.roleId" size="mini">
        <el-radio-button label="1682730217149665281">医院/药店</el-radio-button>
        <el-radio-button label="1682730323424940034">企业</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item prop="account">
      <el-input size="small"
                v-model="loginForm.account"
                auto-complete="off"
                :placeholder="$t('login.username')">
        <i slot="prefix" class="icon-yonghu"/>
      </el-input>
    </el-form-item>
    <el-form-item prop="phone">
      <el-input size="small"
                v-model="loginForm.phone"
                auto-complete="off"
                placeholder="请输入手机号">
        <i slot="prefix" class="icon-shouji"/>
      </el-input>
    </el-form-item>
    <el-form-item prop="name">
      <el-input size="small"
                v-model="loginForm.name"
                auto-complete="off"
                placeholder="请输入姓名">
        <i slot="prefix" class="el-icon-edit"/>
      </el-input>
    </el-form-item>
    <el-form-item prop="passwordRegister">
      <el-input size="small"
                :type="passwordType"
                v-model="loginForm.passwordRegister"
                auto-complete="off"
                :placeholder="$t('login.password')">
        <i class="el-icon-view el-input__icon" slot="suffix" @click="showPassword"/>
        <i slot="prefix" class="icon-mima"/>
      </el-input>
    </el-form-item>
    <el-form-item prop="passwordAgain">
      <el-input size="small"
                :type="passwordType"
                v-model="loginForm.passwordAgain"
                auto-complete="off"
                placeholder="请再次输入密码">
        <i class="el-icon-view el-input__icon" slot="suffix" @click="showPassword"/>
        <i slot="prefix" class="icon-mima"/>
      </el-input>
    </el-form-item>
    <el-form-item prop="captchaCode">
      <el-row :span="24">
        <el-col :span="16">
          <el-input size="small"
                    v-model="loginForm.captchaCode"
                    auto-complete="off"
                    :placeholder="$t('login.code')">
            <i slot="prefix" class="icon-yanzhengma"/>
          </el-input>
        </el-col>
        <el-col :span="8">
          <div class="login-code">
            <img :src="loginForm.image" class="login-code-img" @click="refreshCode"
            />
          </div>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item>
      <el-button type="primary"
                 size="small"
                 @click.native.prevent="handleLogin"
                 class="login-submit">提交注册
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {mapGetters} from "vuex";
import {info} from "@/api/system/tenant";
import {getCaptcha, register} from "@/api/user";
import {getTopUrl} from "@/util/util";
import md5 from 'js-md5'

export default {
  name: "register",
  data() {
    return {
      tenantMode: this.website.tenantMode,
      loginForm: {
        //租户ID
        tenantId: "000000",
        //部门ID
        deptId: "",
        //角色ID
        roleId: "",
        //用户名
        account: "",
        //密码
        passwordRegister: "",
        //账号类型
        type: "account",
        //验证码的值
        captchaCode: "",
        //验证码的索引
        captchaKey: "",
        //预加载白色背景
        image: "",
        passwordAgain: '',
        phone: '',
      },
      registerRules: {
        tenantId: [
          {required: false, message: "请输入租户ID", trigger: "blur"}
        ],
        account: [
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请输入用户名'))
                return
              }
              if (!(/^[a-z][0-9a-z]{7,15}$/).test(value)) {
                callback(new Error('用户名由8-15为英文小写字母加数字组成，必须以字母开头'))
                return
              }
              callback()
            }
          }
        ],
        roleId: [
          {
            trigger: 'blur', required: true, message: '请选择注册类型'
          }
        ],
        phone: [
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请输入手机号'))
                return
              }
              if (!(/^1(3|4|5|6|7|8|9)\d{9}$/).test(value)) {
                callback(new Error('请输入正确手机号码'))
                return
              }
              callback()
            }
          }
        ],
        name: [
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请输入用户姓名'))
                return
              }
              if (!(/^[\u4e00-\u9fa50-9a-zA-Z]{2,32}$/).test(value)) {
                callback(new Error('请输入正确的姓名'))
                return
              }
              callback()
            },
          }
        ],
        passwordRegister: [
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请输入密码'))
                return
              }
              if (!(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[`~#$@!%*?&^()\-_=+])[A-Za-z\d`~#$@!%*?&^()\-_=+]{8,16}$/).test(value)) {
                callback(new Error('密码要求8-16位，至少1个大写字母，1个小写字母，1个数字和1个特殊字符（`~!@#$%^&*()-=_+）'))
                return
              }
              callback()
            }
          }
        ],
        passwordAgain: [
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请输入密码'))
                return
              }
              if (!(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[`~#$@!%*?&^()\-_=+])[A-Za-z\d`~#$@!%*?&^()\-_=+]{8,16}$/).test(value)) {
                callback(new Error('密码要求8-16位，至少1个大写字母，1个小写字母，1个数字和1个特殊字符（`~!@#$%^&*()-=_+）'))
                return
              }
              if (value !== this.loginForm.passwordRegister) {
                callback(new Error('两次输入的密码不一样'))
                return
              }
              callback()
            }
          }
        ],
        captchaCode: [
          {
            trigger: 'blur', required: true, message: '请输入图形验证码'
          }
        ]
      },
      passwordType: "password",
      userBox: false,
      userForm: {
        deptId: '',
        roleId: ''
      },
      userOption: {
        labelWidth: 70,
        submitBtn: true,
        emptyBtn: false,
        submitText: '登录',
        column: [
          {
            label: '部门',
            prop: 'deptId',
            type: 'select',
            props: {
              label: 'deptName',
              value: 'id'
            },
            dicUrl: '/api/blade-system/dept/select',
            span: 24,
            display: false,
            rules: [{
              required: true,
              message: "请选择部门",
              trigger: "blur"
            }],
          },
          {
            label: '角色',
            prop: 'roleId',
            type: 'select',
            props: {
              label: 'roleName',
              value: 'id'
            },
            dicUrl: '/api/blade-system/role/select',
            span: 24,
            display: false,
            rules: [{
              required: true,
              message: "请选择角色",
              trigger: "blur"
            }],
          },
        ]
      }
    };
  },
  created() {
    this.getTenant();
    this.refreshCode();
  },
  mounted() {
  },
  watch: {
    'loginForm.deptId'() {
      const column = this.findObject(this.userOption.column, "deptId");
      if (this.loginForm.deptId.includes(",")) {
        column.dicUrl = `/api/blade-system/dept/select?deptId=${this.loginForm.deptId}`;
        column.display = true;
      } else {
        column.dicUrl = '';
      }
    },
    'loginForm.roleId'() {
      const column = this.findObject(this.userOption.column, "roleId");
      if (this.loginForm.roleId.includes(",")) {
        column.dicUrl = `/api/blade-system/role/select?roleId=${this.loginForm.roleId}`;
        column.display = true;
      } else {
        column.dicUrl = '';
      }
    }
  },
  computed: {
    ...mapGetters(["tagWel", "userInfo"])
  },
  props: [],
  methods: {
    refreshCode() {
      getCaptcha().then(res => {
        const data = res.data;
        this.loginForm.captchaKey = data.key;
        this.loginForm.image = data.image;
      })
    },
    showPassword() {
      this.passwordType === ""
        ? (this.passwordType = "password")
        : (this.passwordType = "");
    },
    submitLogin (form, done) {
      if (form.deptId !== '') {
        this.loginForm.deptId = form.deptId;
      }
      if (form.roleId !== '') {
        this.loginForm.roleId = form.roleId;
      }
      this.handleLogin();
      done();
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '数据提交中,请稍后。。。',
            spinner: "el-icon-loading"
          });
          // 注册
          register({
            ...this.loginForm,
            passwordRegister: md5(this.loginForm.passwordRegister),
            passwordAgain: md5(this.loginForm.passwordAgain),
          }).then(({ data }) => {
            console.log('register returns: ', data)
            if (data.success) {
              this.$message({
                type: 'success',
                message: '注册成功，请登录后完善信息',
                duration: 3000,
              })
              setTimeout(() => {
                window.location.reload();
              }, 2500)
            }
          }).catch((err) => {
            console.log('register fail: ', err)
          }).finally(() => {
            loading.close();
          })
        }
      });
    },
    getTenant() {
      let domain = getTopUrl();
      // 临时指定域名，方便测试
      //domain = "https://bladex.vip";
      info(domain).then(res => {
        const data = res.data;
        if (data.success && data.data.tenantId) {
          this.tenantMode = false;
          this.loginForm.tenantId = data.data.tenantId;
          this.$parent.$refs.login.style.backgroundImage = `url(${data.data.backgroundUrl})`;
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.register-page {
  color: black;
}
</style>
